package top.malaoshi.netdisk.ctrl;

import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.DispatcherServlet;
import top.malaoshi.netdisk.vo.JsonResult;
import top.malaoshi.util.DateTime;
import top.malaoshi.web.utils.Ajax;
import top.malaoshi.web.utils.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class MyBasicErrorController extends BasicErrorController {

    @Override
    public Object error(HttpServletRequest request, HttpServletResponse response, Exception e) {

        HttpStatus status = getStatus(request);
        if(Ajax.isAjax(request)){
            try {
                Map map = new HashMap();
                map.put("timestamp", DateTime.now("yyyy-MM-dd HH:mm:ss.SSS"));
                map.put("status",status.value());
                map.put("error",status.getReasonPhrase());
                map.put("message",e.getMessage());
                map.put("path",request.getServletPath());
                JsonResult jsonResult = JsonResult.fail(status.value(), e.getMessage(), map);
                ResponseUtils.sendJSON(response,status.value(), jsonResult);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }else{
            if(status.value() == 404){
                String servletPath = request.getContextPath();
                try {
                    response.sendRedirect(servletPath);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }

        return null;
    }

}
